<script setup lang="ts">
import { ref } from 'vue'
import PageSkeleton from './components/PageSkeleton.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types'
import { useGuessPullupLoad } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerList = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryList = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotList = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerList(), getHomeCategoryList(), getHomeHotList()])
  isLoading.value = false
})

// 上拉加载猜你喜欢数据
const { guessRef, onScrolltolower } = useGuessPullupLoad()

// 下拉刷新首页数据
const isRefresh = ref(false)
const onRefresherrefresh = async () => {
  isRefresh.value = true
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerList(),
    getHomeCategoryList(),
    getHomeHotList(),
    guessRef.value?.getMore(),
  ])
  isRefresh.value = false
}
</script>

<template>
  <view class="viewport">
    <!-- 自定义导航栏 -->
    <CustomNavbar />
    <scroll-view
      class="scroll-view"
      scroll-y
      enable-back-to-top
      refresher-enabled
      :refresher-triggered="isRefresh"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="onScrolltolower"
    >
      <!-- 骨架屏 -->
      <PageSkeleton v-if="isLoading" />
      <template v-else>
        <!-- 轮播图 -->
        <XtxSwiper :list="bannerList" />
        <!-- 分类面板 -->
        <CategoryPanel :list="categoryList" />
        <!-- 热门推荐 -->
        <HotPanel :list="hotList" />
        <!-- 猜你喜欢 -->
        <XtxGuess ref="guessRef" />
      </template>
    </scroll-view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: #f7f7f7;
  overflow: hidden;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.scroll-view {
  flex: 1;
  overflow: hidden;
}
</style>
